'use strict';
const db = uniCloud.database();
const cart = db.collection('cart');
exports.main = async (event, context) => {
	if(event.cart_type == 0){
	//cart_type = 0做加入购物车和增加数量操作
		let res = await add_cart(event);
		return res
	}else if(event.cart_type == 1){
	//获取用户制定购物车
		let res = await obtain_cart(event);
		return res
	}else if(event.cart_type == 2){
	//更新购物车的数量
		let res = await up_cart(event);
		return res
	}else if(event.cart_type == 3){
	//删除指定购物车
		let res = await del_cart(event);
		return res
	}
};

//加入购物车和增加数量操作
const add_cart = async (event) => {
	let select = await cart.where({
		user_id:event.user_id,
		product_id:event.product_id,
		product_name: event.product_name,
		product_price: event.product_price,
		product_title_image: event.product_title_image,
		effect_off: true
	}).count();
	if(select.total == 0){
		delete event.cart_type
		event.effect_off = true;
		event.effect_time = 15;
		event.updata_cart = event.create_cart;
		let bus = await cart.add(event);
		if(bus.id){
			return {status:200,id:bus.id,msg:'购物车添加成功'}
		}else {
			return {status:200,id:bus.id,msg:'购物车添加失败'}
		}
	}else {
		let res = await cart.where({
			user_id:event.user_id,
			product_id:event.product_id,
			product_name: event.product_name,
			product_price: event.product_price,
			product_title_image: event.product_title_image,
			effect_off: true
		}).get();
		let cart_num = res.data[0].product_number;
		cart_num = res.data[0].product_number + event.product_number;
		let updata = await cart.where({
			user_id:event.user_id,
			product_id:event.product_id,
			product_name: event.product_name,
			product_price: event.product_price,
			product_title_image: event.product_title_image,
			effect_off: true
		}).update({
			product_number: cart_num
		});
		return updata
	}
}

//获取制定用户的购物车
const obtain_cart = async (event) => {
	let ob_cart = await cart.where({
		user_id:event.user_id
	}).get();
	return ob_cart;
}

//用户在购物车列表操作购物车
const up_cart = async (event) => {
	let count = await cart.where({
		create_cart: event.create_cart,
		effect_off: event.effect_off,
		effect_time: event.effect_time,
		product_additional: event.product_additional,
		product_id: event.product_id,
		product_name: event.product_name,
		product_option: event.product_option,
		product_price: event.product_price,
		product_title_image: event.product_title_image,
		user_id: event.user_id
	}).count();
	if(count.total == 1){
		delete event.cart_type
		let id = event._id;
		delete event._id
		event.updata_cart = new Date().getTime();
		let up = await cart.where({
			_id: id
		}).update(event);
		return up
	}else {
		return {
			code: 404,msg:'失败，库存不足'
		}
	}
}

//用户删除购物车
const del_cart = async (event) => {
	let res = cart.where({
		_id: event._id
	}).remove();
	return res
}